package cn.hznc.controller.service.configure;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hznc.configuration.SystemInit;
import cn.hznc.domain.entity.ConfigurationEntity;
import cn.hznc.domain.request.configure.AddComReq;
import cn.hznc.mapper.ConfigurationMapper;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author：Administrator
 * @Date：2023/11/9 11:47
 */
@Service
public class ConfigureService{

    @Resource
    private ConfigurationMapper configurationMapper;
    public Object addCom(AddComReq addComReq){
        if(ObjectUtil.isNull(addComReq.getId())){
            ConfigurationEntity configurationEntity = new ConfigurationEntity();
            BeanUtil.copyProperties(addComReq , configurationEntity);
            configurationMapper.insert(configurationEntity);
        }else {
            ConfigurationEntity configurationEntity = new ConfigurationEntity();
            BeanUtil.copyProperties(addComReq , configurationEntity);
            configurationMapper.updateById(configurationEntity);
        }
        //更新内存map中的值
        Object o = SystemInit.configurationMap.get(addComReq.getConfigureKey());
        if(ObjectUtil.isNotNull(o)){
            List<String> strings = JSONArray.parseArray(o.toString(), String.class);
            if(!strings.contains(addComReq.getConfigureValue())){
                strings.add(addComReq.getConfigureValue());
                SystemInit.configurationMap.put("com" , JSONArray.toJSONString(strings));
            }
        }
        return Boolean.TRUE;
    }

    public Object queryCom(String com) {
        QueryWrapper<ConfigurationEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("configure_key" , com);
        return configurationMapper.selectList(wrapper);
    }

    public Object deleteCom(Integer id) {
        return configurationMapper.deleteById(id);
    }
}
